package com.huaxinkaiye.utils;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.UUID;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

import com.android.volley.Response;

import android.graphics.Bitmap;
import android.util.Log;

/**
 * * * 实现文件上传的工具类
 * 
 * @version 1.0
 */
public class FileImageUpload {
	private static final String TAG = "uploadFile";
	private static final int TIME_OUT = 10 * 10000000; // 超时时间
	private static final String CHARSET = "utf-8"; // 设置编码
	public static final String SUCCESS = "1";
	public static final String FAILURE = "0";

	/**
	 * * android上传文件到服务器
	 * 
	 * @param file
	 *            需要上传的文件
	 * @param RequestURL
	 *            请求的rul
	 * @return 返回响应的内容
	 */
	public static String uploadFile(File file, String RequestURL) {
		String BOUNDARY = UUID.randomUUID().toString(); // 边界标识 随机生成
		String PREFIX = "--", LINE_END = "\r\n";
		String CONTENT_TYPE = "multipart/form-data"; // 内容类型
		try {
			URL url = new URL(RequestURL);
			HttpURLConnection conn = (HttpURLConnection) url.openConnection();
			conn.setReadTimeout(TIME_OUT);
			conn.setConnectTimeout(TIME_OUT);
			conn.setDoInput(true); // 允许输入流
			conn.setDoOutput(true); // 允许输出流
			conn.setUseCaches(false); // 不允许使用缓存
			conn.setRequestMethod("POST"); // 请求方式
			conn.setRequestProperty("Charset", CHARSET);
			// 设置编码
			conn.setRequestProperty("connection", "keep-alive");
			conn.setRequestProperty("Content-Type", CONTENT_TYPE + ";boundary="
					+ BOUNDARY);
			if (file != null) {
				/** * 当文件不为空，把文件包装并且上传 */
				OutputStream outputSteam = conn.getOutputStream();
				DataOutputStream dos = new DataOutputStream(outputSteam);
				StringBuffer sb = new StringBuffer();
				sb.append(PREFIX);
				sb.append(BOUNDARY);
				sb.append(LINE_END);
				/**
				 * 这里重点注意： name里面的值为服务器端需要key 只有这个key 才可以得到对应的文件
				 * filename是文件的名字，包含后缀名的 比如:abc.png
				 */
				sb.append("Content-Disposition: form-data; name=\"picture\"; filename=\""
						+ file.getName() + "\"" + LINE_END);
				sb.append("Content-Type:image/pjpeg; charset=" + CHARSET
						+ LINE_END);
				sb.append(LINE_END);
				dos.write(sb.toString().getBytes());

				Bitmap bitmap = UtilHelper.getBitmapFromFile(file, 1280, 720);
				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos);
				byte[] data = baos.toByteArray();
				dos.write(data);
				// InputStream is = new FileInputStream(file);
				// byte[] bytes = new byte[1024];
				// int len = 0;
				// while ((len = is.read(bytes)) != -1) {
				// dos.write(bytes, 0, len);
				// }
				// is.close();
				dos.write(LINE_END.getBytes());
				byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINE_END)
						.getBytes();
				dos.write(end_data);
				dos.flush();
				/**
				 * 获取响应码 200=成功 当响应成功，获取响应的流
				 */
				int res = conn.getResponseCode();
				Log.e(TAG, "response code:" + res);
				if (res == 200) {
					StringBuilder str = new StringBuilder();
					InputStream ins = conn.getInputStream();
					BufferedInputStream bis = new BufferedInputStream(ins);
					InputStreamReader isr = new InputStreamReader(bis, "utf-8");
					BufferedReader buffer = new BufferedReader(isr);

					for (String s = buffer.readLine(); s != null; s = buffer
							.readLine()) {
						str.append(s);
					}
					buffer.close();
					// array = new JSONArray(str.toString());
					Log.e(TAG, "response content:" + str.toString());
					return str.toString();
					// return SUCCESS;
				}
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return FAILURE;
	}

	public static String postFile(String url, List<NameValuePair> nameValuePairs) {
		HttpClient httpClient = new DefaultHttpClient();
		  // 请求超时
		httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000);
        // 读取超时
		httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 30000);
		HttpContext localContext = new BasicHttpContext();
		HttpPost httpPost = new HttpPost(url);	
//		httpPost.setHeader(HTTP.CONTENT_TYPE,
//                "application/form-data;charset=UTF-8");
        // Add your data
        // Execute HTTP Post Request
		//request.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=utf-8");
		try {
			if (null != SimpleClient.JSESSIONID) {
				httpPost.setHeader("Cookie", "JSESSIONID=" + SimpleClient.JSESSIONID);
				Log.e("JSESSIONID2", SimpleClient.JSESSIONID+"");
			}
			MultipartEntity entity = new MultipartEntity(
					HttpMultipartMode.BROWSER_COMPATIBLE);
			for (int index = 0; index < nameValuePairs.size(); index++) {
				if (nameValuePairs.get(index).getName()
						.equalsIgnoreCase("pictureFile")) {
					// If the key equals to "image", we use FileBody to transfer the data
					entity.addPart(nameValuePairs.get(index).getName(),
							new FileBody(new File(nameValuePairs.get(index)
									.getValue())));
				} else {
					// Normal string data
					entity.addPart(
							nameValuePairs.get(index).getName(),
							new StringBody(nameValuePairs.get(index).getValue(),Charset.forName("UTF-8")));
				}
			}
			httpPost.setEntity(entity);
			HttpResponse response = httpClient.execute(httpPost, localContext);
			
			if (response.getStatusLine().getStatusCode() == 200) {
				/* 读返回数据 */
				String strResult = EntityUtils.toString(response.getEntity());
				return strResult;
			} else {
				return "failds";
			}
		} catch (IOException e) {
			e.printStackTrace();
			return e.toString();
		}

	}

}
